package controllers;

import java.util.List;

import org.bouncycastle.jce.provider.JDKDSASigner.stdDSA;

import play.mvc.Controller;
import ch.bfh.abch.rems.REMSMulticastController;
import ch.bfh.abch.rems.sender.tinkerforge.TFMulticastSender;
import ch.bfh.abcm.rems.SensorControllerFactory;
import ch.bfh.abcm.rems.konfiguration.EventMessage;
import ch.bfh.abcm.rems.konfiguration.EventMessage.EventType;
import ch.bfh.abcm.rems.sensors.tinkerforge.TFSensorController;
import controllers.tinkerforge.REMSTFConfig;
import controllers.tinkerforge.REMSTFSensorDataPersister;
import controllers.validation.SensorJobStarter;

public class SensorConfigController extends Controller {

    private static REMSTFSensorDataPersister dataPersister = new REMSTFSensorDataPersister();
    private static REMSTFConfig config = new REMSTFConfig(dataPersister);
    private static TFSensorController sensorController;
    private static TFMulticastSender sender = new REMSMulticastController().getMulticastSender();

    public static void sensors() {
        List<models.SensorConfig> sensorConfigList = models.SensorConfig.findAll();
        sensorController = createSensorController();
        render(sensorConfigList);
    }

    public static void startValidationJob() {
        SensorJobStarter validation = new SensorJobStarter();
        validation.startValidationJob();
        sensors();
    }

    public static void loadSensorConfig() {
        createSensorController().updateSensorList();
        sender.sendEventMessage(new EventMessage(EventType.UPDATE_SENSORCONFIG));
        sensors();
    }

    public static void startDataMining() {
        createSensorController().connectToAvailableSensors();
        sender.sendEventMessage(new EventMessage(EventType.START_DATAMINING));
        sensors();
    }

    public static void stopDataMining() {
        sender.sendEventMessage(new EventMessage(EventType.STOP_DATAMINING));
        createSensorController().disconnectSensors();
        sensors();
    }

    public static void enableDatamining(boolean enable) {
        if (enable) {
            createSensorController().connectToAvailableSensors();
        } else {
            createSensorController().disconnectSensors();;
        }
    }

    public static void updateSensorList() {
        createSensorController().updateSensorList();
    }

    public static TFSensorController getSensorController() {
        return createSensorController();
    }
    
    private static TFSensorController createSensorController() {
        if (sensorController == null) {
            sensorController = SensorControllerFactory.getTFSensorController(config);
        }
        return sensorController;
    }
}
